import { Button, Card, message, Popconfirm, Switch, Table, Tag } from 'antd';
import React, { useEffect, useState } from 'react';

import DictionaryService from '@/api/services/stars/dictionaryService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import DictionaryModal from '@/pages/setting/dictionary/dictionary-modal';
import DictionaryForm from '@/pages/setting/dictionary/search-form';
import SubDictionaryData from '@/pages/setting/dictionary/sub-data';
import { datetime } from '@/utils/format-date';
import { hasPermission } from '@/utils/permission';

import { Dictionaries } from './type';

import { ListData, PageForm } from '#/entity';
import type { ColumnsType } from 'antd/es/table';

const defaultDictionaryValue: Dictionaries = {
  key: '',
  name: '',
  system: false,
  status: true,
  sort: 0,
};

function DictionaryPage() {
  // 状态管理
  const [dataSource, setDataSource] = useState<ListData<Dictionaries>>();
  const [searchForm, setSearchForm] = useState<PageForm>({
    page: 1,
    take: 10,
  });

  const [modalProps, setModalProps] = useState({
    show: false,
    title: '',
    formValue: defaultDictionaryValue,
    onOk: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      setSearchForm((prev) => ({ ...prev, page: 1 }));
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
    },
  });

  const onCreate = () => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '新增字典',
      formValue: {
        ...defaultDictionaryValue,
      },
    }));
  };
  // 获取信息
  useEffect(() => {
    DictionaryService.list(searchForm).then((res) => {
      setDataSource(res);
    });
  }, [searchForm]);
  const onEdit = (row: Dictionaries) => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改字典',
      formValue: row,
    }));
  };

  // search
  const onReset = () => {
    setSearchForm({ page: 1, take: 10 });
  };
  const onSearch = (data: PageForm) => {
    setSearchForm({ page: 1, take: searchForm.take, ...data });
  };
  const handleDelete = (id: string) => {
    DictionaryService.remove({ ids: [id] }).then((res) => {
      if (res > 0) {
        message
          .open({
            content: '删除成功',
            type: 'success',
            duration: 1,
          })
          .then(() =>
            setSearchForm({
              page:
                dataSource?.data.length === 1 && searchForm.page > 1
                  ? searchForm.page - 1
                  : searchForm.page,
              take: searchForm.take,
            }),
          );
      }
    });
  };
  // 展开子表格
  const expandedRowRender = (record: Dictionaries) => {
    return (
      <div style={{ marginLeft: 50 }}>
        <SubDictionaryData parentId={record.id} />
      </div>
    );
  };

  // 表格列配置
  const columns: ColumnsType<Dictionaries> = [
    {
      title: '字典名称',
      dataIndex: 'name',
      align: 'center',
      width: 150,
    },
    {
      title: '字典键',
      dataIndex: 'key',
      align: 'center',
      width: 150,
      render: (type) => {
        return <Tag color="processing">{type}</Tag>;
      },
    },
    {
      title: '启用状态',
      dataIndex: 'status',
      align: 'center',
      render: (status, dictionaries: Dictionaries) => {
        return (
          <Switch
            disabled={!hasPermission('STARS:DICTIONARIES:UPDATE')}
            checked={status}
            onChange={(status: boolean) => {
              const updateForm: Dictionaries = {
                status,
                key: dictionaries.key,
                system: dictionaries.system,
              };

              DictionaryService.edit(dictionaries.id, updateForm).then((res) => {
                setSearchForm({
                  page:
                    dataSource?.data.length === 1 && searchForm.page > 1
                      ? searchForm.page - 1
                      : searchForm.page,
                  take: searchForm.take,
                });
              });
            }}
          />
        );
      },
    },
    {
      title: '系统内置',
      dataIndex: 'system',
      align: 'center',
      render: (system, dictionaries: Dictionaries) => {
        return (
          <Switch
            disabled={!hasPermission('STARS:DICTIONARIES:UPDATE')}
            checked={system}
            onChange={(system: boolean) => {
              const updateForm: Dictionaries = {
                system,
                key: dictionaries.key,
                status: dictionaries.status,
              };

              DictionaryService.edit(dictionaries.id, updateForm).then((res) => {
                setSearchForm({
                  page:
                    dataSource?.data.length === 1 && searchForm.page > 1
                      ? searchForm.page - 1
                      : searchForm.page,
                  take: searchForm.take,
                });
              });
            }}
          />
        );
      },
    },
    {
      title: '字典说明',
      dataIndex: 'remark',
      align: 'center',
      width: 180,
      render: (type) => {
        return <Tag color="pink">{type}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      align: 'center',
      width: 180,
      render: (createAt: string) => {
        return datetime(createAt);
      },
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'createBy',
      minWidth: 100,
      render: (createBy) => {
        return createBy.name;
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 120,
      render: (_, record) => (
        <div className="flex justify-center gap-2">
          {hasPermission('STARS:DICTIONARIES:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="修改">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('STARS:DICTIONARIES:DELETE') && (
            <Popconfirm
              title="确认删除吗?"
              okText="确定"
              cancelText="取消"
              onConfirm={() => handleDelete(record.id)}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  return (
    <div>
      <DictionaryForm onOk={onSearch} onReset={onReset} />
      <br />
      <Card
        title="字典管理"
        extra={
          <Button
            type="primary"
            disabled={!hasPermission('STARS:DICTIONARIES:CREATE')}
            onClick={() => {
              onCreate();
            }}
          >
            新增
          </Button>
        }
      >
        <Table
          size="small"
          rowKey="id"
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={dataSource?.data}
          expandable={{
            expandedRowRender,
          }}
          pagination={{
            current: searchForm.page,
            pageSize: searchForm.take,
            total: dataSource?.count, // 新增：总条目数
            // showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, size) => {
              setSearchForm((prev) => ({ ...prev, page, take: size }));
            },
          }}
          style={{ marginTop: 20 }}
        />
        <DictionaryModal {...modalProps} />
      </Card>
    </div>
  );
}

export default DictionaryPage;
